<?php

/**
 * 动态
 */

namespace app\api\controller\user;

use app\api\controller\Common;
use think\facade\Env as getEnv;
use GatewayWorker\Lib\Gateway;
//require '../extend/AipImageCensor/Censor.php';
class Cart extends Common
{
    protected $data;
    public function initialize()
    {
        parent::initialize();
        $this->data = $this->request->except(['sign', 'accessKey', 'token']);
    }

    /**
     * 加入购物车
     */
    public function addGoods()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $goods_id = $this->data['goods_id'];
        $sku_id = $this->data['sku_id'];
        $goods_num = $this->data['goods_num'];
        
        $data = $this->data;
        $data['user_id'] = $this->user['id'];
        $data['create_time'] = date("Y-m-d H:i:s", time());
        if (!input('goods_id') || !input('sku_id')) {
            $this->showError('参数错误', '403');
        }

        // 商品信息
        $detail = db('goods_info')->alias('a')->where('a.id', $goods_id)
            ->field('a.id,a.name,a.code,a.sale_price,a.original_price,a.stock,a.status,a.desc,a.content,a.brand_id')
            ->find();
        if (!$detail) {
            $this->showError('商品不存在', '404');
        }
        $data['brand_id'] = $detail['brand_id'];
        $data['goods_name'] = $detail['name'];
        $data['goods_info'] = $detail;
        // 商品SKU
        $goods_sku = db('goods_info_sku')->field('id,desc,price,agent_price,stock')->where('id', $sku_id)->find();
        if($goods_sku['stock'] - $goods_num < 0){
            $this->showError('库存不足', '405');
        }
        $data['sku_name'] = $goods_sku['desc'];

        //加盟商价格判断
        $is_agent = $this->checkAgent($detail['brand_id']);
        if($is_agent){
            $data['sku_price'] = $goods_sku['agent_price'];
        }
        else{
            $data['sku_price'] = $goods_sku['price'];
        }
        // 商品图片
        $pic = db('goods_info_pic')->field('id,pic')->where('gid', $goods_id)->find();
        $data['goods_pic'] = $pic['pic'];

        //是否加入过
        $cart = db('goods_cart')->where(['user_id'=>$user_id, 'goods_id'=> $goods_id, 'sku_id'=> $sku_id])->find();
        if($cart){
            $res = db('goods_cart')->where(['user_id' => $user_id, 'goods_id' => $goods_id, 'sku_id' => $sku_id])->update(
                [
                    'goods_num'=>$cart['goods_num'] + $goods_num,
                    'sku_price'=> $data['sku_price'],
                    'create_time'=> $data['create_time']
                ]
            );
        }
        else{
            $res = db('goods_cart')->json(['goods_info'])->insert($data);
        }
        if ($res) {
            return $this->showSuccess('添加购物车成功');
        } else {
            return $this->showError('添加购物车失败');
        }
    }

    /**
     * 购物车商品列表
     */
    public function list()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $list = db('goods_cart')->alias('a')->where('a.user_id', $user_id)
            ->field('a.id,a.brand_id,b.title as brand_name,a.goods_id,a.goods_name,a.goods_num,a.sku_id,a.sku_name,c.price,c.agent_price,a.goods_pic,c.stock')
            ->leftJoin('goods_category b', 'b.id = a.brand_id')
            ->leftJoin('goods_info_sku c', 'a.sku_id=c.id')
            ->select();
        foreach ($list as $key => $val) {
            $is_agent = $this->checkAgent($val['brand_id']);
            if ($is_agent) {
                $list[$key]['sku_price'] = $val['agent_price'];
            } else {
                $list[$key]['sku_price'] = $val['price'];
            }
            unset($list[$key]['price'], $list[$key]['agent_price']);
        }
        return $this->showSuccess('购物车列表', $list);
    }

    /**
     * 修改购物车商品数量
     */
    public function setGoodsNum()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $id = $this->data['id'];
        $goods_num = $this->data['goods_num'];
        $cart = db('goods_cart')->where(['id' => $id])->find();
        if(!$cart){
            return $this->showError('购物车商品不存在', '404');
        }
        if ($cart['user_id'] != $user_id) {
            return $this->showError('无权操作', '401');
        }

        $res = db('goods_cart')->where(['id' => $id])->update(
            [
                'goods_num' => $goods_num
            ]
        );
        return $this->showSuccess('修改购物车商品数量成功');
    }

    /**
     * 删除购物车商品
     *
     * @return void
     */
    public function delGoods()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $data = $this->data;
        $ids = $data['ids'];
        if(!is_array($ids)){
            $ids = json_decode($ids, true);
        }

        if (!$ids || !is_array($ids)) {
            $this->showError('参数错误', '403');
        }

        db('goods_cart')->where(['id' => $ids, 'user_id'=>$user_id])->delete();
        return $this->showSuccess('删除购物车商品成功');

    }


    /**
     * 购物车结算商品列表
     */
    public function settleList()
    {
        $this->checkUserLogin(); // 验证登录
        $user_id = $this->user['id'];
        $cart_ids = input('ids', []);
        $list = db('goods_cart')->alias('a')
            ->field('a.id,a.brand_id,b.title as brand_name,a.goods_id,a.goods_name,a.goods_num,a.sku_id,a.sku_name,c.price,c.agent_price,a.goods_pic,c.stock')
            ->join('goods_category b', 'b.id = a.brand_id')
            ->leftJoin('goods_info_sku c', 'a.sku_id=c.id')
            ->where('a.user_id', $user_id)
            ->where('a.id', 'in', $cart_ids)
            ->select();
        $amout = 0;
        foreach($list as $key=>$val){
            if($val['stock'] < $val['goods_num']){
                $this->showError('商品 '.$val['goods_name'].' 库存不足', '405');
            }
            $is_agent = $this->checkAgent($val['brand_id']);
            if($is_agent){
                $list[$key]['sku_price'] = $val['agent_price'];
            }
            else{
                $list[$key]['sku_price'] = $val['price'];
            }
            $amout += $list[$key]['sku_price'] * $val['goods_num'];
            unset($list[$key]['price'], $list[$key]['agent_price']);
        }
        $account = db('users')->where('id', $user_id)->value('account');
        $append = [
            'amount'=> sprintf('%.2f', $amout),
            'transport'=> '5.00',
            'account'=> $account,
        ];
        return $this->showSuccess('购物车结算列表', $list, $append);
    }
}
